package com.sqlist.share.connection;

import android.os.Message;
import android.util.Log;

import com.sqlist.share.MainActivity;
import com.sqlist.share.dto.LinkDTO;
import com.sqlist.share.dto.MessageDTO;
import com.sqlist.share.resolver.DataResolverProxy;
import com.sqlist.share.util.Const;
import com.sqlist.share.util.GsonUtils;

import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.SimpleChannelInboundHandler;
import io.netty.util.CharsetUtil;

/**
 * Created by SqList on 2018/6/11.
 */

public class ClientHandler extends SimpleChannelInboundHandler<String> {
    private static final String TAG = "Share - ClientHandler";

    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        Log.i(TAG, "channelActive");

        MessageDTO<LinkDTO> linkDTOMessageDTO = new MessageDTO<>();
        linkDTOMessageDTO.setCode(Const.REQUEST);
        linkDTOMessageDTO.setMsg("建立连接");
        linkDTOMessageDTO.setType("linkDTO");
        linkDTOMessageDTO.setUsername(Const.USERNAME);
        linkDTOMessageDTO.setToken(Const.TOKEN);
        linkDTOMessageDTO.setData(new LinkDTO());

        byte[] req = (GsonUtils.getInstance().toJson(linkDTOMessageDTO) + "|").getBytes();
        ByteBuf byteBuf;
        byteBuf = Unpooled.buffer(req.length);
        byteBuf.writeBytes(req);
        ctx.writeAndFlush(byteBuf);
    }

    @Override
    protected void channelRead0(ChannelHandlerContext ctx, String msg) throws Exception {
        Log.i(TAG, "channelRead " + msg);
        DataResolverProxy.getSingleton().doAction(msg, ctx.channel());
    }

    @Override
    public void channelInactive(ChannelHandlerContext ctx) throws Exception {
        Log.i(TAG, "Client Close");
        Message message = new Message();
        message.what = LinkDTO.LINK_ERROR;
        MainActivity.getHandler().sendMessage(message);
        ctx.close();
    }

    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        cause.printStackTrace();
        ctx.close();
    }
}
